import { reqGoodsInfo, reqAddOrUpdateShopCart } from "@/api"
import { getUUID } from "@/util/uuid_token"

// 仓库存储数据
const state = {
  goodInfo: {},
  uuid_token: getUUID()
}
// 修改state的唯一手段
const mutations = {
  GETGOODINFO(state, goodInfo) {
    state.goodInfo = goodInfo
  },
}
// 处理action，可以书写自己的业务逻辑，也可以处理异步
const actions = {
  // 获取商品详情
  async getGoodInfo({ commit }, skuId) {
    let result = await reqGoodsInfo(skuId)
    if (result.code == 200) {
      commit('GETGOODINFO', result.data)
    }
  },
  // 加入购物车
  async addOrUpdateShopCart({ commit }, payload) {
    const { skuId, skuNum } = payload;
    let result = await reqAddOrUpdateShopCart(skuId, skuNum);
    console.log('完整响应结果:', result);
    // console.log('响应状态码（HTTP）:', result.status);
    // console.log('响应体（业务数据）:', result.data);
    if (result.code == 200 || result.code == 201) {
      return 'ok'
    } else {
      return Promise.reject(new Error(`失败，业务状态码: ${result.data?.code || '无'}`));
    }
  },
}
// 类似于计算属性
const getters = {
  categoryView(state) {
    return state.goodInfo.categoryView || {}
  },
  skuInfo(state) {
    return state.goodInfo.skuInfo || {}
  },
  spuSaleAttrList(state) {
    return state.goodInfo.spuSaleAttrList || []
  }
}

export default {
  state,
  mutations,
  actions,
  getters
}